package com.example.controller;

import com.example.controller.utils.R;
import com.example.domain.*;
import com.example.service.ManagerService;
import com.example.service.OptionService;
import com.example.service.QuestionnaireService;
import com.example.service.UserService;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/manager")
public class ManagerController {

    @Autowired
    ManagerService managerService;

    @Autowired
    UserService userService;

    @Autowired
    QuestionnaireService questionnaireService;

    @Autowired
    OptionService optionService;

    int num = 0;

    /**
     * 登陆界面
     */
    @PostMapping("/login")
    public String login(@RequestParam("username")String username, @RequestParam("password")String password, HttpSession session,
                        HttpServletRequest request, HttpServletResponse response){
        boolean result=managerService.login(username,password);
        int num = managerService.getManagerCount();
        int num1 = questionnaireService.getQuestionnaireCount();
        int num2 = userService.getUserCount();

        int num5 = questionnaireService.getQuestionnaireCount(0);
        int num6 = questionnaireService.getQuestionnaireCount(1);
        int num7 = questionnaireService.getQuestionnaireCount(2);
        double bili = ((double) num6+(double) num7)/num2;
        String bili2 = bili*100+"%";

        session.setAttribute("questionnaireNum",num1);
        session.setAttribute("userNum",num2);

        session.setAttribute("passNum",num6);
        session.setAttribute("nocheck",num5);
        session.setAttribute("nopassNum",num7);
        session.setAttribute("bili",bili2);

        session.setAttribute("typeM",num);
        session.setAttribute("typeU","user");
        session.setAttribute("typeQ","questionnaire");

        if(result) {
            Cookie cookie = new Cookie("isLogin","success");
            cookie.setMaxAge(60*60*24);
            cookie.setPath("/");
            response.addCookie(cookie);
            session.setAttribute("isLogin", username);
            session.setAttribute("manager",managerService.findByUsername(username));
            return "redirect:/manager/home/manage";
        }
        else {
            request.setAttribute("message","账号或密码错误，请重新输入");
            return "ManagerLogin";
        }
    }

    @RequestMapping("/login")
    public String login1(){
       return "ManagerLogin";
    }

    /**
     * 用户管理界面
     */
    //修改用户名，使用put请求,返回修改后的user对象
    @PutMapping("/users/{username}")
    public String updateName(@PathVariable("username")String username1,@RequestParam("username")String username2,Model model){
        //将要修改的用户名用url保存，input修改后的username
        User user=userService.findByUsername(username1);
        user.setUsername(username2);
        model.addAttribute(user);
        return "ManagerUser";
    }

    //查询用户，使用get请求,返回要查询的user对象
    @GetMapping("/users/{username}")
    public String getUser(@PathVariable("username")String username,Model model){
        User user=userService.findByUsername(username);
        model.addAttribute(user);
        return "ManagerUser";
    }

    //查询用户，使用get请求,返回要查询的user对象
    @GetMapping("/users/{page}/{size}")
    public String getUsers(@PathVariable("page")int currentPage,@PathVariable("size")int pageSize,Model model){

        model.addAttribute(userService.getUsers(currentPage,pageSize));
        return "ManagerUser";
    }


    //修改密码，使用post请求,返回修改后的user对象
    @PostMapping("/users/{username}")
    public String updatePsd(@PathVariable("username")String username,@RequestParam("password")String password,Model model){
        //将要修改的用户名用url保存，input修改后的password
        User user=userService.findByUsername(username);
        user.setPassword(password);
        model.addAttribute(user);
        return "ManagerUser";
    }

    /**
     * 管理员管理界面
     */
    //返回所有管理员，使用get请求
    @GetMapping("/managers")
    public String managers(){
        return "ManagerManager";
    }

    @GetMapping("/managers/allManager")
    public String managers3(HttpServletRequest request, HttpServletResponse response,HttpSession session){
        //返回所有管理员，用一个容器来存放，元素即为管理员对象
        String act=request.getParameter("act");
        String val=request.getParameter("userid");
        System.out.println(act);
        System.out.println(val);
        if(act.equals("load")) {
            try {
                request.setCharacterEncoding("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            response.setContentType("text/json; charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONArray jsonarray = new JSONArray();

            List<Manager> managerList = managerService.getManagers(1, 10).getRecords();

            int count = 0;

            for (Manager manager2 : managerList) {
                JSONObject jsonobj = new JSONObject();
                count++;
                String str = count + "";
                jsonobj.put("id", str);
                jsonobj.put("username", manager2.getUsername());
                jsonobj.put("password", manager2.getPassword());
                if (manager2.getIsMale() == 1) {
                    jsonobj.put("sex", "男");
                } else {
                    jsonobj.put("sex", "女");
                }
                jsonobj.put("phone", manager2.getPhoneNum());
                jsonobj.put("email", manager2.getEmail());
                if (manager2.getIsSuper() == 1) {
                    jsonobj.put("remark", "超级管理员");
                } else {
                    jsonobj.put("remark", "普通管理员");
                }
                jsonarray.add(jsonobj);

            }
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (out != null) {
                out.println(jsonarray);
            } else {
                System.out.println("空");
            }
            System.out.println(jsonarray);

        } else if(act.equals("del")) {
            managerService.delete(val);
            return "ManagerManager";

        } else if(act.equals("edit")){
            session.setAttribute("manager2",managerService.findByUsername(val));
            return "ManagerProfile2";

        }else if(act.equals("back")) {

            return "ManagerManager";
        }
        return null;

    }

    @GetMapping("/managers/allSurvey")
    public String managersSuervey(HttpServletRequest request, HttpServletResponse response,HttpSession session){
        //返回所有管理员，用一个容器来存放，元素即为管理员对象
        String act1=request.getParameter("act1");
        String val=request.getParameter("userid");
        Manager manager = (Manager) session.getAttribute("manager");

        System.out.println(act1);
        System.out.println(val);
        if(act1.equals("load")) {
            try {
                request.setCharacterEncoding("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            response.setContentType("text/json; charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONArray jsonarray = new JSONArray();

            List<Questionnaire> questionnaires = questionnaireService.getQuestionnaires(1,10).getRecords();

            List<Questionnaire> questionnaires1 = questionnaireService.getQuestionnaires(1,10).getRecords();

            for (Questionnaire questionnaire : questionnaires){
                if(!(questionnaire.getManagerName().equals(manager.getUsername()))){
                    questionnaires1.remove(questionnaire);
                }
            }


            if (questionnaires1 != null) {
                for (Questionnaire questionnaire : questionnaires1) {
                    JSONObject jsonobj = new JSONObject();

                    jsonobj.put("id", questionnaire.getQuestionnaireId());
                    jsonobj.put("creator", questionnaire.getCreator());
                    jsonobj.put("title", questionnaire.getTitle());
                    jsonobj.put("managerUsername", questionnaire.getManagerName());
                    if (questionnaire.getStatus() == 0) {
                        jsonobj.put("status", "未审核");
                    } else if(questionnaire.getStatus() == 1) {
                        jsonobj.put("status", "审核通过");
                    } else if(questionnaire.getStatus() == 2){
                        jsonobj.put("status", "审核未通过");
                    }
                    jsonobj.put("questionCount",questionnaire.getQuestionCount());

                    jsonarray.add(jsonobj);

                }
            }
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (out != null) {
                out.println(jsonarray);
            } else {
                System.out.println("空");
            }
            System.out.println(jsonarray);

        } else if(act1.equals("check")){

            Questionnaire questionnaire = questionnaireService.findById(Integer.parseInt(val));
            System.out.println(questionnaire.getStatus());
            session.setAttribute("questionnaire", questionnaire);
            List<Question> questionList =questionnaireService.getQuestions(Integer.parseInt(val));
            session.setAttribute("questionList",questionList );
            List<Option> optionList = optionService.getOption2(Integer.parseInt(val));
            session.setAttribute("optionList",optionList );
            System.out.println(optionList);

            return "ManagerUserFilling";

        }else if(act1.equals("back")) {

            return "ManagerSurvey";
        }
        return null;

    }

    @GetMapping("/managers/allUser")
    public String managers4(HttpServletRequest request, HttpServletResponse response,HttpSession session){
        //返回所有管理员，用一个容器来存放，元素即为管理员对象
        String act=request.getParameter("act");
        String val=request.getParameter("userid");
        System.out.println(act);
        System.out.println(val);
        if(act.equals("load")) {
            try {
                request.setCharacterEncoding("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            response.setContentType("text/json; charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONArray jsonarray = new JSONArray();

            List<User> userList = userService.getUsers(1,10).getRecords();

            int count = 0;

            for (User user : userList) {
                JSONObject jsonobj = new JSONObject();
                count++;
                String str = count + "";
                jsonobj.put("id", str);
                jsonobj.put("username", user.getUsername());
                jsonobj.put("password", user.getPassword());
                jsonobj.put("phone", user.getPhoneNum());
                jsonarray.add(jsonobj);
            }
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (out != null) {
                out.println(jsonarray);
            } else {
                System.out.println("空");
            }
            System.out.println(jsonarray);

        }  else if(act.equals("edit")){
            session.setAttribute("user2",userService.findByUsername(val));
            return "ManagerProfile3";

        }else if(act.equals("back")) {

            return "ManagerUser";
        }
        return null;

    }

    @PostMapping("/managers/{page}/{size}")
    public String managers2(@PathVariable("page")String currentPage,@PathVariable("size")String pageSize,Model model){
        //返回所有管理员，用一个容器来存放，元素即为管理员对象
        model.addAttribute(managerService.getManagers(Integer.parseInt(currentPage),Integer.parseInt(pageSize)).getRecords());
        return "ManagerManager";
    }

        //新增管理员
    @GetMapping("/managers/add")
    public String add(@RequestParam("username")String username,@RequestParam("password")String password,
                      @RequestParam("sex")String sex,@RequestParam("phonenumber")String phonenumber,
                      @RequestParam("email")String email,@RequestParam("remark")String remark,HttpServletRequest request,
                      HttpSession session) {

        Manager manager = new Manager();

        Manager manager1 = managerService.findByUsername(username);

           Pattern pattern = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}");//\w表示a-z，A-Z，0-9(\\转义符)

           Matcher matcher = pattern.matcher(email);

         if (Objects.equals(username, "")) {
            request.setAttribute("message", "用户名为空，请重新输入");
        } else if(manager1!=null){
             request.setAttribute("message", "用户名已存在，请重新输入");
        }else if (Objects.equals(password, "")) {
            request.setAttribute("message", "密码为空，请重新输入");
        } else if(email.equals("")){
               request.setAttribute("message", "请输入邮箱");
           }else if (!(matcher.matches())) {
             request.setAttribute("message", "邮箱格式错误，请重新输入");
         }
        else if(Objects.equals(remark, "")){
            request.setAttribute("message", "权限为空，请重新输入");
        }
        else if(!(remark.equals("超级管理员")  || remark .equals("普通管理员") )){
            request.setAttribute("message", "权限格式不正确，请重新输入");
        }
        else if(Objects.equals(sex, "")){
            request.setAttribute("message", "请输入性别");
        }
        else if(!(Objects.equals(sex, "男") || Objects.equals(sex, "女"))){
            request.setAttribute("message", "性别格式不正确，请重新输入");
        }
        else if(Objects.equals(phonenumber, "")){
            request.setAttribute("message", "请输入电话号码");
        }
        else {
            manager.setUsername(username);
            manager.setPassword(password);
            if (sex.equals("男")) {
                manager.setIsMale(1);
            } else {
                manager.setIsMale(0);
            }
            if (remark.equals("超级管理员")) {
                manager.setIsSuper(1);
            } else {
                manager.setIsSuper(0);
            }
            manager.setPhoneNum(phonenumber);
            manager.setEmail(email);
            managerService.add(manager);
        }
        return "ManagerManager";
    }


    //删除管理员，使用delete请求
    @DeleteMapping("/managers/{username}")
    public String deleteM(@RequestParam("username")String username){
        //根据用户名删除指定管理员
        managerService.delete(username);
        return "ManagerManager";
    }
    //删除管理员，使用delete请求
    @DeleteMapping("/managers/delete")
    public String delete2(){
        //根据用户名删除指定管理员
        return "ManagerManager";
    }

    //查询管理员，使用get请求,返回一个manager对象
    @GetMapping("/managers/{username}")
    public String getManager(@RequestParam("username")String username,Model model){
        //根据用户名返回指定管理员
        Manager manager=managerService.findByUsername(username);
        model.addAttribute(manager);
        return "ManagerManager";
    }

    /**
     * 问卷审核界面
     */
    //返回所有问卷，使用get请求，返回一个问卷容器
    @RequestMapping("/questionnaires")
    public String questionnaires(){
        return "ManagerSurvey";
    }

    //查询问卷，使用get请求
    @GetMapping("/questionnaires/{id}")
    public String findQ(@PathVariable("id")int id,Model model){
        //使用方法返回指定问卷。
        Questionnaire questionnaire=questionnaireService.findById(id);
        model.addAttribute(questionnaire);
        return "ManagerSurvey";
    }

    //审核不通过，使用delete请求
    @DeleteMapping("/questionnaires/{id}")
    public String deleteQ(@PathVariable("id") int id){
        //根据id删除指定问卷
        questionnaireService.delete(id);
        return "ManagerSurvey";
    }


    /**
     *管理员信息界面
     */
    //返回该管理员所有信息，使用get请求,返回了一个manager对象
    @GetMapping("/profile/{username}")
    public String findManager(@PathVariable("username")String username,Model model){
        model.addAttribute(managerService.findByUsername(username));
        return "ManagerProfile";
    }

    @RequestMapping("/profile/{username}")
    public String message(){
        //进入管理员信息界面，返回用管理员信息界面jsp的名称
        return "ManagerProfile";
    }

    //修改管理员信息，使用put请求
    @PutMapping("/profile")
    public String updateUser(@RequestBody Manager manager,Model model){
        //返回更新后的manager对象
        model.addAttribute(managerService.modify(manager));
        return "ManagerProfile";
    }

    @RequestMapping(value = "/update")
    public String update(HttpSession session, HttpServletRequest request) {
        Manager manager = (Manager) session.getAttribute("manager");
        if(!Objects.equals(request.getParameter("email"), "")) {
            Pattern pattern=Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}");//\w表示a-z，A-Z，0-9(\\转义符)

            Matcher matcher=pattern.matcher(request.getParameter("email"));

           if(matcher.matches()) {
               manager.setEmail(request.getParameter("email"));
           }
           else {
               request.setAttribute("message", "邮箱格式错误，请重新输入");
               System.out.println("邮箱格式错误，请重新输入");
           }
        }else {
            request.setAttribute("message", "邮箱为空，请重新输入");
            System.out.println("邮箱为空，请重新输入");
            return "ManagerProfile";
        }

        if(!Objects.equals(request.getParameter("phone"), "")) {
            manager.setPhoneNum(request.getParameter("phone"));
        }else {
            request.setAttribute("message", "电话为空，请重新输入");
            System.out.println("电话为空，请重新输入");
            return "ManagerProfile";
        }

        if(request.getParameter("gender2").equals("先生")){
           manager.setIsMale(1);
        } else {
            manager.setIsMale(0);
        }

        if(!Objects.equals(request.getParameter("password"), "")) {
            manager.setPassword(request.getParameter("password"));
        }else {
            request.setAttribute("message", "密码为空，请重新输入");
            System.out.println("密码为空，请重新输入");
            return "ManagerProfile";
        }
        session.setAttribute("manager",managerService.modify(manager));
        return "ManagerProfile";
    }

    @RequestMapping(value = "/update2")
    public String update3(HttpSession session, HttpServletRequest request) {
        Manager manager = (Manager) session.getAttribute("manager2");
        if(!Objects.equals(request.getParameter("email"), "")) {
            Pattern pattern=Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}");//\w表示a-z，A-Z，0-9(\\转义符)

            Matcher matcher=pattern.matcher(request.getParameter("email"));

            if(matcher.matches()) {
                manager.setEmail(request.getParameter("email"));
            }
            else {
                request.setAttribute("message", "邮箱格式错误，请重新输入");
                System.out.println("邮箱格式错误，请重新输入");
            }
        }else {
            request.setAttribute("message", "邮箱为空，请重新输入");
            System.out.println("邮箱为空，请重新输入");
            return "ManagerProfile2";
        }

        if(!Objects.equals(request.getParameter("phone"), "")) {
            manager.setPhoneNum(request.getParameter("phone"));
        }else {
            request.setAttribute("message", "电话为空，请重新输入");
            System.out.println("电话为空，请重新输入");
            return "ManagerProfile2";
        }

        if(request.getParameter("gender2").equals("先生")){
            manager.setIsMale(1);
        } else {
            manager.setIsMale(0);
        }

        if(request.getParameter("gender3").equals("超级管理员")){
            manager.setIsSuper(1);
        } else {
            manager.setIsSuper(0);
        }

        if(!Objects.equals(request.getParameter("password"), "")) {
            manager.setPassword(request.getParameter("password"));
        }else {
            request.setAttribute("message", "密码为空，请重新输入");
            System.out.println("密码为空，请重新输入");
            return "ManagerProfile2";
        }
        session.setAttribute("manager2",managerService.modify(manager));
        return "ManagerProfile2";
    }

    @RequestMapping(value = "/update3")
    public String update4(HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute("user2");

        if(!Objects.equals(request.getParameter("password"), "")) {
           user.setPassword(request.getParameter("password"));
        }else {
            request.setAttribute("message", "密码为空，请重新输入");
            System.out.println("密码为空，请重新输入");
            return "ManagerProfile3";
        }
        if(!Objects.equals(request.getParameter("phone"), "")) {
            user.setPhoneNum(request.getParameter("phone"));
        }else {
            request.setAttribute("message", "电话为空，请重新输入");
            System.out.println("电话为空，请重新输入");
            return "ManagerProfile3";
        }
        session.setAttribute("usr2",userService.modify(user));
        return "ManagerProfile3";
    }


    /**
     * 管理员主页
     */
    @GetMapping("/home/manage")
    public String manage(){
        //进入管理员管理界面，返回管理界面jsp的名称
        return "ManagerHome";
    }

    @RequestMapping("/home/client")
    public String client(){
        //进入用户管理界面，返回用户管理界面jsp的名称
        return "ManagerUser";
    }


    @RequestMapping("/home/check")
    public String check(){
        //进入问卷审核界面，返回问卷审核界面jsp的名称
        return "ManagerSurvey";
    }

    @RequestMapping("/editState")
    public String editState(HttpSession session){
        Questionnaire questionnaire =(Questionnaire) session.getAttribute("questionnaire");
        questionnaire.setStatus(1);
        session.setAttribute("questionnaire",questionnaireService.modify(questionnaire));
        return "ManagerSurvey";
    }

    @RequestMapping("/editState2")
    public String editState2(HttpSession session){
        Questionnaire questionnaire =(Questionnaire) session.getAttribute("questionnaire");
        questionnaire.setStatus(2);
        session.setAttribute("questionnaire",questionnaireService.modify(questionnaire));
        return "ManagerSurvey";
    }

}
